package com.gblfy.ws.client;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.stereotype.Component;

/**
 * cxf客户端调用（企业内部已封装）
 *
 * @author gblfy
 * @date 2021-09-17
 */
@Component
public class CxfClient {
    public static void main(String[] args) throws Exception {
        String cxfUrl = "http://127.0.0.1:8080/cxf/cxfServiceShell?wsdl";
        String method = "sayhello";
        String reqXml = "1";

        //调用服务
        CxfClient.cxfClientParam(cxfUrl, method, reqXml);
    }

    /**
     * 单/多参调用工具类（Object类型）
     *
     * @param cxfUrl url地址
     * @param method 调用方法名
     * @param reqXml 发送报文体
     * @return res 返回结果
     * @throws Exception 若有异常，在控制台输出异常，并将异常抛出
     */
    public static String cxfClientParam(String cxfUrl, String method, Object... reqXml) throws Exception {
        String res = null;
        // 创建动态客户端
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(cxfUrl);

        // 需要密码的情况需要加上用户名和密码
        // client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME, PASS_WORD));
        Object[] objects = new Object[0];
        try {
            // 基本格式:invoke("方法名",参数1,参数2,参数3....);
            objects = client.invoke(method, reqXml);
            res = objects[0].toString();
            System.out.println("返回数据:" + res);
        } catch (java.lang.Exception e) {
            e.printStackTrace();
            throw e;
        }
        return res;
    }
}
